package cn.lycode.common.core.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public interface Treeable<T> {
    Object getId();

    Object getPid();

    List<T> getChildren();

    void setChildren(List<T> children);


    static <T extends Treeable<T>> List<T>  buildTreeVO(List<T> treeVOList) {
        Map<Object, T> map = new HashMap<>();
        for (T item : treeVOList) {
            map.put(item.getId(), item);
        }

        List<T> rootList = new ArrayList<>();

        for (T item : treeVOList) {
            //无父节点
            if (item.getPid() == null || item.getPid().equals(0L)) {
                // This is a root menu item
                rootList.add(item);
            } else {
                // This is a child menu item, find its parent
                T parent = map.get(item.getPid());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(item);
                }
            }
        }

        return rootList;
    }
}